package kotlinx.benchmarks.json

import kotlinx.benchmarks.model.*
import kotlinx.serialization.json.*
import org.openjdk.jmh.annotations.*
import java.io.OutputStream
import java.util.concurrent.*

@Warmup(iterations = 7, time = 1)
@Measurement(iterations = 5, time = 1)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
@Fork(2)
open class TwitterBenchmark {

    /*
     * Twitter feed benchmark.
     *
     * This is a small piece of twitter feed taken from one of the simdjson repository
     * with Kotlin classes generated by Json2Kotlin plugin (and also manually adjusted)
     */
    private val input = TwitterBenchmark::class.java.getResource("/twitter.json").readBytes().decodeToString()
    private val twitter = Json.decodeFromString(Twitter.serializer(), input)

    private val jsonImplicitNulls = Json { explicitNulls = false }

    private val devNullStream = object : OutputStream() {
        override fun write(b: Int) {}
        override fun write(b: ByteArray) {}
        override fun write(b: ByteArray, off: Int, len: Int) {}
    }

    @Setup
    fun init() {
        require(twitter == Json.decodeFromString(Twitter.serializer(), Json.encodeToString(Twitter.serializer(), twitter)))
    }

    // Order of magnitude: 4-7 op/ms
    @Benchmark
    fun decodeTwitter() = Json.decodeFromString(Twitter.serializer(), input)

    @Benchmark
    fun decodeTwitterImplicitNulls() = jsonImplicitNulls.decodeFromString(Twitter.serializer(), input)

    @Benchmark
    fun encodeTwitter() = Json.encodeToString(Twitter.serializer(), twitter)

    @Benchmark
    fun encodeTwitterStream() = Json.encodeToStream(Twitter.serializer(), twitter, devNullStream)
}
